#include "headfile.h"

sbit clk = P2 ^ 7;
sbit cs = P2 ^ 6;
sbit din = P2 ^ 5;
sbit dout = P2 ^ 4;
/********************************************************************
 SPI发送一个字节
 *********************************************************************/
void spi_write(uint8 data_spi) //适用于上升沿发送,先发送高位的器件
{
    uint8 i = 8;
    clk = 0;
    while (i--)
    {
        din = data_spi >> 7;
        data_spi <<= 1;
        clk = 1; //上升沿发送
        clk = 0;
    }
}

/********************************************************************
 SPI读取一个字节
 *********************************************************************/
uint16 spi_read()
{
    uint8 wei;
    uint16 data_read = 0;
    wei = 12; //12位和8位由控制位决定
    clk = 1;
    while (wei--)
    {
        data_read <<= 1;
        data_read |= dout;
        clk = 0;
        clk = 1;
    }
    return data_read;
}

/********************************************************************
 SPI读取模拟信号
 *********************************************************************/
uint16 read_ad_data(uint8 cmd)
{
    uint16 data_ad;
    data_ad = 0;
    cs = 0;
    clk = 0;
    spi_write(cmd);
    data_ad = spi_read();
    cs = 1;
    return data_ad;
}